package com.ztom.agent.util;

import com.ztom.agent.common.PropertyKeys;
import com.ztom.agent.common.PropertyValues;
import com.ztom.agent.log.Logger;

import java.io.File;
import java.net.URLDecoder;
import java.util.Objects;

/**
 * @author ZhangTao
 */
public class JarToolUtils {

    public static String getJarCurrentPath() {
        File jarFile = getJarFile();
        if (Objects.isNull(jarFile)) {
            return null;
        }
        return jarFile.getAbsolutePath();
    }

    public static String getJarCurrentDir() {
        File jarFile = getJarFile();
        if (Objects.isNull(jarFile)) {
            return null;
        }
        return jarFile.getParent();
    }

    public static String getJarName() {
        File jarFile = getJarFile();
        if (Objects.isNull(jarFile)) {
            return null;
        }
        return jarFile.getName();
    }

    private static File getJarFile() {
        String filePath = JarToolUtils.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        try {
            filePath = URLDecoder.decode(filePath, "UTF-8");
            return new File(filePath);
        }catch (Exception e) {
            Logger.error("JarToolUtils.getJarFile()", e);
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(System.getProperty(PropertyKeys.LOG_FILE_PATH, PropertyValues.DEFAULT_LOG_FILE_PATH));
    }
}
